package demo.spring.boot.jdbc;

import demo.spring.boot.jdbc.entity.Department;
import demo.spring.boot.jdbc.entity.Role;
import demo.spring.boot.jdbc.entity.User;
import demo.spring.boot.jdbc.repository.DepartmentRepository;
import demo.spring.boot.jdbc.repository.RoleRepository;
import demo.spring.boot.jdbc.repository.UserRepository;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * Created by lushun.chen on 2017/4/15.
 *
 * @author lushun.chen
 */
@RestController
@RequestMapping
public class DemoController {

    private static Logger logger = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    UserRepository userRepository;
    @Autowired
    DepartmentRepository departmentRepository;
    @Autowired
    RoleRepository roleRepository;

    @RequestMapping("/1")
    public void save() {
        userRepository.deleteAll();
        departmentRepository.deleteAll();
        roleRepository.deleteAll();

        Department department = new Department();
        department.setName("开发部");
        departmentRepository.save(department);

        Role role = new Role();
        role.setName("admin");
        roleRepository.save(role);
        Assert.assertNotNull(role.getId());

        User user = new User();
        user.setName("张三");
        user.setCreateDate(new Date());
        user.setDepartment(department);
        List<Role> roleList = roleRepository.findAll();
        Assert.assertNotNull(roleList);
        user.setRoles(roleList);
        userRepository.save(user);
        Assert.assertNotNull(user);
    }

    @RequestMapping("/2")
    public Page<User> findPage() {
        Pageable pageable = new PageRequest(0, 10, new Sort(Sort.Direction.ASC, "id"));
        Page<User> page = userRepository.findAll(pageable);
        Assert.assertNotNull(page);
        for (User user : page.getContent()) {
            logger.info(user.getName());
        }
        return page;
    }
}
